package com.farm.code.jdbc;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JdbcUtil {
	/* 获取数据库连接的函数 */
	public static Connection getConnection(DataSourceConf conf) {
		Connection con = null; // 创建用于连接数据库的Connection对象
		try {
			Class.forName(conf.getDriverClassName());// 加载Mysql数据驱动
			con = DriverManager.getConnection(conf.getUrl(),
					conf.getUsername(), conf.getPassword());// 创建数据连接
		} catch (Exception e) {
			System.out.println("数据库连接失败" + e.getMessage());
		}
		return con; // 返回所建立的数据库连接
	}

	public static List<Map<String, Object>> getFieldType(DataSourceConf conf,
			String tableName) throws Exception {
		Connection con = JdbcUtil.getConnection(conf);
		List<Map<String, Object>> fields = new ArrayList<Map<String, Object>>();
		DatabaseMetaData dmd = con.getMetaData();
		ResultSet rs = dmd.getColumns(null, null, tableName, null);
		while (rs.next()) {
			Map<String, Object> field = new HashMap<String, Object>();
			field.put("NAME", rs.getString("COLUMN_NAME"));
			field.put("SIZE", rs.getString("COLUMN_SIZE"));
			field.put("NULLABLE", rs.getString("NULLABLE"));
			field.put("TYPE", rs.getString("TYPE_NAME"));
			field.put("FFORMTYPE", "text");
			field.put("TITLE", rs.getString("COLUMN_NAME"));
			fields.add(field);
		}
		return fields;
	}

	public static List<String> getTables(DataSourceConf conf) throws Exception {
		DatabaseMetaData meta;
		List<String> tables = new ArrayList<String>();
		Connection con = JdbcUtil.getConnection(conf);
		try {
			meta = con.getMetaData();
			ResultSet rs = meta.getTables(null, null, null,
					new String[] { "TABLE" });
			while (rs.next()) {
				tables.add(rs.getString(3));
			}
		} catch (Exception e) {
			throw new Exception(e);
		} finally {
			con.close();
		}
		return tables;
	}
}
